#include "guiElement.h"

using namespace sde;

GuiElement::GuiElement(std::string _type, std::string _name, Object* _object) :
    Action("GuiElement",_type,_name,_object),
    window(0),
    parentWindow(0),
    windowManager(0),
    gfxServer(0) {
    initDepend = "gfx/GfxServer";
}

void GuiElement::run() {
    gfxServer = (GfxServer*)Action::getFirstActionOfArchetype("gfx/GfxServer");
    
    if (gfxServer) {
        windowManager = gfxServer->getGuiWindowManager();
        if (windowManager) {
            window = makeWindow(windowManager);
            
            if (window) {
                updateParent(object->getVar("parent",Var(std::string(""))));
                object->subscribeSetVar("parent",boost::bind(&GuiElement::updateParent,this,_1));
                
                updatePosition(object->getVar("position",Var(Vector2(0,0))));
                object->subscribeSetVar("position",boost::bind(&GuiElement::updatePosition,this,_1));
                
                updateSize(object->getVar("size",Var(Vector2(1,1))));
                object->subscribeSetVar("size",boost::bind(&GuiElement::updateSize,this,_1));
            }
        }
    } else
        log("ERROR: couldn't find gfxServer");
}

CEGUI::Window* GuiElement::makeWindow(CEGUI::WindowManager* windowManager) {
    return 0;
}

void GuiElement::stop() {
    if (windowManager && window)
        windowManager->destroyWindow(window);
}

void GuiElement::updateParent(Var val) {
    if (parentWindow && parentWindow->isChild(window))
        parentWindow->removeChildWindow(window);
        
    parentWindow = 0;
    
    if (boost::any_cast<std::string>(&val)) {
        std::string parentName = boost::any_cast<std::string>(val);
        Object* parentObject = object->getObject(parentName);
        if (parentObject) {
            GuiElement* guiElement = (GuiElement*)parentObject->getFirstActionOfArchetype("GuiElement");
            if (guiElement)
                parentWindow = guiElement->window;
        }
    }
    
    if (!parentWindow && gfxServer)
        parentWindow = gfxServer->getGuiSheet();
        
    if (parentWindow && window)
        parentWindow->addChildWindow(window);
}

void GuiElement::updatePosition(Var val) {
    if (boost::any_cast<Vector2>(&val) && window) {
        Vector2 v = boost::any_cast<Vector2>(val);
        window->setPosition(CEGUI::UVector2(CEGUI::UDim(v.x,0),CEGUI::UDim(v.y,0)));
    }
}

void GuiElement::updateSize(Var val) {
    if (boost::any_cast<Vector2>(&val) && window) {
        Vector2 v = boost::any_cast<Vector2>(val);
        window->setSize(CEGUI::UVector2(CEGUI::UDim(v.x,0),CEGUI::UDim(v.y,0)));
    }
}
